package com.cw.interceptor;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.cw.common.api.ResultObject;
import com.cw.common.constant.TokenConstant;
import com.cw.config.JwtConfig;
import io.swagger.models.HttpMethod;
import org.springframework.stereotype.Component;
import com.cw.util.StringUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author cc
 * @Date 2020/6/28 17:41
 * @Version 1.0 Token拦截器
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //         地址过滤
        String uri = request.getRequestURI();
        String test = request.getHeader(jwtConfig.getHeader());
        // 如果不是映射到方法直接通过
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        //去除不需要校验的接口名
        if (uri.contains("/login") || uri.contains("/token") || uri.contains("/error") || uri.contains("app") || uri.contains("Excel") || uri.contains("/his-cwgl-bed/getEemptyBedsListNew")
                || uri.contains("/this-ii-prepayin")
                || uri.contains("/his-cwgl-bed/getReservationRjssDetail")
                || uri.contains("/this-ii-prepayin/getThisIiPrepayinByPreid")
                || uri.contains("/patient-bed-middle-rjss/addPatientBed")
                || uri.contains("/patient-bed-middle-rjsz/getIiPrepayinByIdRJ")
                || uri.contains("/patient-bed-middle-rjsz/searchRJSZ")
                || uri.contains("/patient-bed-middle-rjsz/searchRJSS")
                || uri.contains("/patient-bed-middle-rjsz/addPatientBed")
                || uri.contains("/patient-bed-middle-rjsz/delPatientBed")
                || uri.contains("/patient-bed-middle-prebundled/updateTrueBinding")
                || uri.contains("/RjbfCenterController/cancellation")
                || uri.contains("/his-cwgl-bed/getKongBedList")
                || uri.contains("/this-ii-prepayin/getmedicalGroup")
                || uri.contains("/this-ii-prepayin/getmedicalGroupLeader")
                || uri.contains("/VYqBrdjxxController/getReportList")
                || uri.contains("/VYqBrdjxxController/getReportListDownLoadExcel")
                || uri.contains("/VYqBrdjxxController/getReportListIntegrated")
                || uri.contains("/VYqBrdjxxController/getRJSSReportList")
                || uri.contains("/VYqBrdjxxController/getRJSSReportListIntegrated")
                || uri.contains("/his-cwgl-bed/getEemptyBedsDetailsNew")
                || uri.contains("/his-cwgl-nurse/getWardList")
                || uri.contains("/his-cwgl-dept/getDeptListHis")
                || uri.contains("/his-cwgl-dept/getDeptList")
                || uri.contains("/his-cwgl-dept/getPatientAreaDTO")
                || uri.contains("/his-cwgl-bed/getAllManageBed")
                || uri.contains("/occupation-bed/unUsedOccupationBedVersionTwo")
                || uri.contains("/this-ii-prepayin/changeBedType")
                || uri.contains("/this-ii-prepayin/selectCwInformation")
                || uri.contains("/his-cwgl-bed/getReservationDetail")
                || uri.contains("/websocket")
                || uri.contains("application-bed/getBedReservationQuery")
                || uri.contains("this-ii-prepayin/getThisIiPrepayin")
                || uri.contains("/ext-information/addNonHeaderCalibration" )
                || uri.contains("RjbfCenterController")
                || uri.contains("this-ii-inmaininfo/getPrintHospitalCertificate")
                || uri.contains("/base-dict")
                || uri.contains("/patient-info/getPatientInfoByIdenno")
                || uri.contains("/login2")
                || uri.contains("/getLoginInfo")
                ||uri.contains("/VYqBrdjxxController/listPatientInfoToDoctor")
        )

        {
            return true;
        }
        // Token 验证
        String token = request.getHeader(jwtConfig.getHeader());
        if (StringUtil.isEmpty(token)) {
            token = request.getParameter(jwtConfig.getHeader());
        }
        if (StringUtil.isEmpty(token)) {
            response.setCharacterEncoding("UTF-8");
            response.sendError(510, "token不能为空");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(ResultObject.errorReturn("没有权限")));
            return false;
        }
        Map<String, Object> claims = jwtConfig.getTokenClaim(token);
        if (null == claims || jwtConfig.isTokenExpired(
                DateUtil.date(Long.parseLong(claims.get(TokenConstant.EXP).toString()) * 1000L))) {
            response.setCharacterEncoding("UTF-8");
            response.sendError(510, "token失效,请重新登录");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(ResultObject.errorReturn("没有权限")));
            return false;
        }
        return true;
    }
}
